package com.lzh.chatnote.webSocket;

import cn.hutool.core.net.URLDecoder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class HttpHeadersHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            //UrlBuilder.
            //UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.uri());
            //// 获取token参数
            //String token = Optional.ofNullable(urlBuilder.getQuery())
            //        .map(k->k.get("token")).map(CharSequence::toString).orElse("");
            //
            String token = "";
            if(!"/".equals(request.uri())){
                token = getTokenFromQueryString(request.uri());
            }

            NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token);

            // 获取请求路径
            request.setUri("/");
            HttpHeaders headers = request.headers();
            String ip = headers.get("X-Real-IP");
            if (StringUtils.isEmpty(ip)) {//如果没经过nginx，就直接获取远端地址
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                ip = address.getAddress().getHostAddress();
            }
            NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip);
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(request);
        }else
        {
            ctx.fireChannelRead(msg);
        }
    }

    /**
     * 解析 URL 并返回查询参数
     * @param queryString 待解析的 URL
     * @return 包含查询参数的 Map
     */
    private static String getTokenFromQueryString(String queryString) {
        try {
            // 移除前导的斜杠和问号
            String query = queryString.startsWith("/?") ? queryString.substring(2) : queryString;

            // 分割查询字符串
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                int idx = pair.indexOf("=");
                if (idx > 0) {
                    String key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8);
                    String value = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8);
                    if ("token".equals(key)) {
                        return value;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        // 定义 URL
        String url = "https://example.com/api?key=value&param1=value1&param2=value2";

        // 解析 URL 并取出查询参数
        //Map<String, String> params = parseUrlParams(url);
    }
}
